package org.jeecg.modules.providers.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.constant.CacheConstant;
import org.jeecg.common.constant.CommonConstant;
import org.jeecg.common.constant.RedisPublicKeyPrefixConstant;
import org.jeecg.common.exception.JeecgBootException;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.RedisUtil;
import org.jeecg.modules.providers.entity.MtServiceProviders;
import org.jeecg.modules.providers.mapper.MtServiceProvidersMapper;
import org.jeecg.modules.providers.service.IMtServiceProvidersService;
import org.jeecg.modules.system.entity.SysRole;
import org.jeecg.modules.system.entity.SysUser;
import org.jeecg.modules.system.entity.SysUserRole;
import org.jeecg.modules.system.service.ISysRoleService;
import org.jeecg.modules.system.service.ISysUserRoleService;
import org.jeecg.modules.system.service.ISysUserService;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @Description: 服务商表
 * @Author: jeecg-boot
 * @Date: 2022-08-05
 * @Version: V1.0
 */
@Service
public class MtServiceProvidersServiceImpl extends ServiceImpl<MtServiceProvidersMapper, MtServiceProviders> implements IMtServiceProvidersService {

    private final ISysUserService iSysUserService;
    private final RedisUtil redisUtil;
    private final ISysUserRoleService iSysUserRoleService;
    private final ISysRoleService sysRoleService;
    private final ISysUserService sysUserService;

    public MtServiceProvidersServiceImpl(ISysUserService iSysUserService, RedisUtil redisUtil, ISysUserRoleService iSysUserRoleService, ISysRoleService sysRoleService, ISysUserService sysUserService) {
        this.iSysUserService = iSysUserService;
        this.redisUtil = redisUtil;
        this.iSysUserRoleService = iSysUserRoleService;
        this.sysRoleService = sysRoleService;
        this.sysUserService = sysUserService;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveServiceProvidersAndCreateUser(MtServiceProviders mtServiceProviders) {
        JSONObject user = new JSONObject();
        /**账号：服务商联系人手机号码*/
        user.put("username", mtServiceProviders.getHeadTel());
        user.put("realname", mtServiceProviders.getProName());//用户名称：服务商名称
        user.put("password", mtServiceProviders.getHeadTel()); //密码 ：服务商联系人手机号码
        user.put("phone", mtServiceProviders.getHeadTel()); //用户联系人电话：服务商联系人手机号码
        user.put("confirmpassword", mtServiceProviders.getHeadTel()); //确认密码
        user.put("useridentity", 1); //身份（1 普通成员 2 上级）
        user.put("userId", mtServiceProviders.getUserId());
        user.put("activitisync", 1);//同步工作流引擎(1-同步,0-不同步)
        user.put("contacts", mtServiceProviders.getHeadName());//联系人
        user.put("workNo", mtServiceProviders.getHeadTel());//用户工号：服务商联系人手机号码
        user.put("usertype", 1);//0平台管理员 1服务商 2服务站 3工程师 4客户
        Result<SysUser> userResult = iSysUserService.addUserAndDept(user, CommonConstant.ROLE_SERVICE_PROVIDERS);
        redisUtil.removeAll(CacheConstant.SYS_DEPARTS_CACHE);
        redisUtil.removeAll(CacheConstant.SYS_DEPART_IDS_CACHE);
        if (!userResult.isSuccess()) {
            //手动报错 强制事务回滚
            throw new JeecgBootException(userResult.getMessage());
        }
        // 保存服务商信息
        SysUser result = userResult.getResult();
        mtServiceProviders.setUserId(result.getUsername()) //绑定用户
                .setSysOrgCode(result.getOrgCode()); //当前生成部门
        super.save(mtServiceProviders);
        // 更新用户关联id
        SysUser sysUser = new SysUser();
        sysUser.setId(result.getId())
                .setLinkId(mtServiceProviders.getId());
        sysUserService.updateById(sysUser);
        String string = JSON.toJSONString(mtServiceProviders);
        redisUtil.set(RedisPublicKeyPrefixConstant.PROVIDERS + ":" + mtServiceProviders.getSysOrgCode() + ":" + mtServiceProviders.getCreateBy(), string, 60 * 60 * 2);
    }

    @Override
    public Object getProviderIdByLoginUser() {
        LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();//获取当前登录用户
        //获取当前登录账号的角色
        List<SysUserRole> userList = iSysUserRoleService.list(new LambdaQueryWrapper<SysUserRole>()
                .eq(SysUserRole::getUserId, loginUser.getId()));
        if (userList == null || userList.size() == 0) {
            return Result.error("未检测到此帐号关联的角色!");
        }
        String roleId = userList.get(0).getRoleId();
        //获取角色对象
        SysRole sysRole = sysRoleService.getOne(new LambdaQueryWrapper<SysRole>()
                .eq(SysRole::getId, roleId));
        if (sysRole == null) {
            return Result.error("帐号关联的角色不存在!");
        }
        if (CommonConstant.ROLE_SERVICE_PROVIDERS.equals(sysRole.getRoleCode())) {
            MtServiceProviders mtServiceProviders = this.getOne(new LambdaQueryWrapper<MtServiceProviders>()
                    .eq(MtServiceProviders::getUserId, loginUser.getUsername()));
            if (mtServiceProviders == null) {
                return Result.error("服务商不存在!");
            }
            return mtServiceProviders.getId();
        }
        return null;
    }

    @Override
    public Object getAreaByLoginUser() {
        LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();//2.0版本获取当前登录用户
        //获取当前登录账号的角色
        List<SysUserRole> userList = iSysUserRoleService.list(new LambdaQueryWrapper<SysUserRole>().eq(SysUserRole::getUserId, loginUser.getId()));
        if (userList == null || userList.size() == 0) {
            return Result.error("未检测到此帐号关联的角色!");
        }
        String roleId = userList.get(0).getRoleId();
        LambdaQueryWrapper<SysRole> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysRole::getId, roleId);
        //获取角色对象
        SysRole sysRole = sysRoleService.getOne(wrapper);
        if (sysRole == null) {
            return Result.error("帐号关联的角色不存在!");
        }
        if (CommonConstant.ROLE_SERVICE_PROVIDERS.equals(sysRole.getRoleCode())) {
            LambdaQueryWrapper<MtServiceProviders> mtWrapper = new LambdaQueryWrapper<>();
            mtWrapper.eq(MtServiceProviders::getUserId, loginUser.getUsername());
            MtServiceProviders mtServiceProviders = this.getOne(mtWrapper);
            if (mtServiceProviders == null) {
                return Result.error("服务商不存在!");
            }
            return mtServiceProviders.getId();
        }
        return null;
    }
}
